function clickforrel(event) {
    if (!$('#menu_rel').hasClass('d-none')) {
        return false;
    }
    name_link_node = $('#menu_detail_name a');
    link_href = name_link_node.attr('href');
    if (link_href == undefined) {
        return false;
    }
    $.ajax({
        url: link_href,
        type: 'get',
        success(data) {
            tbody = $('#menu_rel table tbody');
            tbody.empty();
            $.each(data, function (index, value) {
                section = '<tr><td rowspan="2"><a>' + value['title'] + '</a></td><td>'
                    + value['pname'] + '</td></tr><tr><td style="border-top: none">'
                    + value['purl'] + '</td></tr>';
                tbody.append(section);
            });
            $('#menu_rel').removeClass('d-none');
        },
        error(data) {
            console.log(data);
        }
    });
    return false;
}

// 权限添加处理
function add_permission() {
    url = $('#permission_add').attr('href');
    $.ajax({
        url: url,
        type: "POST",
        data: $('#MenuModal form').serialize(),
        success: function (data) {
            $('#MenuModal .modal-body').html(data);
            if (success_flag == true) {
                $('#MenuModal .modal_btn').unbind().addClass('d-none');
                currentnode = zTreeObj.getSelectedNodes()[0];
                zTreeObj.reAsyncChildNodes(currentnode.getParentNode(), 'refresh');
            }
        },
        error: function (data) {
            console.log(data);
        }
    });
}

// 权限修改处理
function edit_permission() {
    url = $('#permission_edit').attr('href').replace('0', selectednode.perid);
    $.ajax({
        url: url,
        type: "POST",
        data: $('#MenuModal form').serialize(),
        success: function (data) {
            $('#MenuModal .modal-body').html(data);
            if (success_flag == true) {
                $('#MenuModal .modal_btn').unbind().addClass('d-none');
                currentnode = zTreeObj.getSelectedNodes()[0];
                zTreeObj.reAsyncChildNodes(currentnode.getParentNode(), 'refresh');
            }
        },
        error: function (data) {
            console.log(data);
        }
    });
}

// 菜单添加处理
function add_menu() {
    let currentnode = hover_treenode;
    $('#MenuModal #id_parent').val(currentnode.id);
    $.ajax({
        url: menu_add_url,
        type: "POST",
        data: $('#MenuModal form').serialize(),
        success: function (data) {
            $('#MenuModal .modal-body').html(data);
            if (success_flag == true) {
                $('#MenuModal .modal_btn').unbind().addClass('d-none');
                if (!currentnode.hasChildren) {
                    currentnode.hasChildren = true;
                }
                zTreeObj.reAsyncChildNodes(currentnode, 'refresh');
            }
        },
        error: function (data) {
            console.log(data);
        }
    });
}

function add_node(event) {
    event.stopPropagation();
    success_flag = false;
    $.ajax({
        url: menu_add_url,
        success: function (data) {
            $('#MenuModal .modal-body').html(data);
            $('#MenuModal .modal-title').text("添加菜单");
            $('#MenuModal .modal-header small').text("菜单名称不可重复，菜单图标可以为空");
            $('#MenuModal .modal_btn').unbind().bind('click', add_menu).removeClass('d-none');
            $('#MenuModal').modal('show');
        },
        error: function (data) {
            console.log(data);
        }
    });
}

// 菜单修改处理
function edit_menu() {
    let currentnode = hover_treenode;
    $('#MenuModal #id_parent').val(currentnode.getParentNode().id);
    let url = menu_edit_url_base.replace('0', currentnode.id);
    $.ajax({
        url: url,
        type: "POST",
        data: $('#MenuModal form').serialize(),
        success: function (data) {
            $('#MenuModal .modal-body').html(data);
            if (success_flag == true) {
                $('#MenuModal .modal_btn').unbind().addClass('d-none');
                zTreeObj.reAsyncChildNodes(currentnode.getParentNode(), 'refresh');
                currentnode.rel = currentnode.children.length;
                zTreeObj.updateNode(currentnode);
            }
        },
        error: function (data) {
            console.log(data);
        }
    });
}

function beforeEditName(treeId, treeNode) {
    success_flag = false;
    let url = menu_edit_url_base.replace('0', treeNode.id);
    $.ajax({
        url: url,
        success: function (data) {
            $('#MenuModal .modal-body').html(data);
            $('#MenuModal .modal-title').text("更新菜单");
            $('#MenuModal .modal-header small').text("菜单名称不可重复，菜单图标可以为空");
            $('#MenuModal .modal_btn').unbind().bind('click', edit_menu).removeClass('d-none');
            $('#MenuModal').modal('show');
        },
        error: function (data) {
            console.log(data);
        }
    });
    return false;
}

// 菜单删除处理
function beforeRemove(treeId, treeNode) {
    if (success_flag != undefined && success_flag.hasOwnProperty('id') && success_flag.id == treeNode.id) {
        success_flag = false;
        return true;
    }
    let url = menu_del_url_base.replace('0', treeNode.id);
    if (treeNode.hasChildren) {
        swal({
            title: "无法删除！",
            text: "此节点下有子节点，请确保此节点下没有子节点再进行删除！",
            icon: "error",
            button: " 确 定 ",
        });
        return false;
    }
    swal({
        title: "Are you sure?",
        text: "Once deleted, you will not be able to recover this node!",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willDelete) => {
        if (willDelete) {
            $.ajax({
                url: url,
                type: "POST",
                data: $('.ibox-content form').serialize(),
                dataType: 'json',
                success: function (data) {
                    parent_node = treeNode.getParentNode();
                    if (data['status'] == 0) {
                        swal({
                            title: "删除成功！",
                            text: "此节点已经成功删除",
                            icon: "success",
                            button: " 确 定 ",
                        });
                        if (parent_node.children.length == 1) {
                            parent_node.hasChildren = false;
                        }
                        delete node_info[treeNode.id];
                        success_flag = treeNode;
                        zTreeObj.removeNode(treeNode);
                        parent_node.ccount = parent_node.children.length;
                        parent_node.name = parent_node.show_name + "(c:" + parent_node.ccount + ")";
                        zTreeObj.updateNode(parent_node);
                    } else {
                        swal({
                            title: "删除失败！",
                            text: "此节点删除失败，失败原因是: " + data['info'],
                            icon: "warning",
                            button: " 确 定 ",
                        });
                    }
                },
                error: function (data) {
                    console.log(data);
                }
            });
        }
    });
    return false;
}

// 显示增删改按钮
// 显示添加按钮并绑定添加处理函数
function addHoverDom(treeId, treeNode) {
    hover_treenode = treeNode;
    if (treeNode.id == 0) {
        treeNode.title = treeNode.show_title;
    } else if (treeNode.isParent) {
        treeNode.title = treeNode.show_title + "children:" + treeNode.ccount.toString();
    } else {
        treeNode.title = treeNode.show_title + "rel:" + treeNode.rel.toString();
    }
    zTreeObj.updateNode(treeNode);
    if (!treeNode.isParent) return false;
    let sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    let addStr = "<span class='button add' id='addBtn_" + treeNode.tId
        + "' title='add node' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    let btn = $("#addBtn_" + treeNode.tId);
    if (btn) {
        btn.bind("click", add_node);
    }
}

// 移除、重命名自定义操作
function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
}

// 根节点不显示重命名和删除按钮
function showRenameeBtn(treeId, treeNode) {
    return !treeNode.level == 0;
}

function showRemoveBtn(treeId, treeNode) {
    return (!treeNode.level == 0 && !treeNode.hasChildren);
}

// 保持单一路径
let curExpandNode = null;

function beforeExpand(treeId, treeNode) {
    let pNode = curExpandNode ? curExpandNode.getParentNode() : null;
    let treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
    for (let i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
        if (treeNode !== treeNodeP.children[i]) {
            zTreeObj.expandNode(treeNodeP.children[i], false);
        }
    }
    while (pNode) {
        if (pNode === treeNode) {
            break;
        }
        pNode = pNode.getParentNode();
    }
    if (!pNode) {
        singlePath(treeNode);
    }

}

function singlePath(newNode) {
    if (newNode === curExpandNode) return;

    let rootNodes, tmpRoot, tmpTId, i, j, n;

    if (!curExpandNode) {
        tmpRoot = newNode;
        while (tmpRoot) {
            tmpTId = tmpRoot.tId;
            tmpRoot = tmpRoot.getParentNode();
        }
        rootNodes = zTreeObj.getNodes();
        for (i = 0, j = rootNodes.length; i < j; i++) {
            n = rootNodes[i];
            if (n.tId != tmpTId) {
                zTreeObj.expandNode(n, false);
            }
        }
    } else if (curExpandNode && curExpandNode.open) {
        if (newNode.parentTId === curExpandNode.parentTId) {
            zTreeObj.expandNode(curExpandNode, false);
        } else {
            let newParents = [];
            while (newNode) {
                newNode = newNode.getParentNode();
                if (newNode === curExpandNode) {
                    newParents = null;
                    break;
                } else if (newNode) {
                    newParents.push(newNode);
                }
            }
            if (newParents != null) {
                let oldNode = curExpandNode;
                let oldParents = [];
                while (oldNode) {
                    oldNode = oldNode.getParentNode();
                    if (oldNode) {
                        oldParents.push(oldNode);
                    }
                }
                if (newParents.length > 0) {
                    zTreeObj.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
                } else {
                    zTreeObj.expandNode(oldParents[oldParents.length - 1], false);
                }
            }
        }
    }
    curExpandNode = newNode;
}

function onExpand(event, treeId, treeNode) {
    curExpandNode = treeNode;
}

function onClick(e, treeId, treeNode) {
    // 展示第二个页面
    name_link_node = $('#menu_detail_name a');
    name_link_node.text(treeNode.pertitle);
    $('#menu_detail_icon').html('<i class="fa ' + treeNode.show_icon + '"></i>');
    $('#menu_detail_permission').text(treeNode.permission);
    $('#menu_detail_code').text(treeNode.aliasname);
    // 第二个页面判断是否添加显示第三个页面的链接并先隐藏第三个页面
    tbody = $('#menu_rel table tbody');
    if (treeNode.rel == 0 || treeNode.id == 0) {
        name_link_node.removeAttr('href');
        tbody.empty();
        $('#menu_rel').addClass('d-none');
    } else {
        name_link_node.attr('href', menu_list_url + "?id=" + treeNode.id + "&nodeload=detail");
        tbody.empty();
        $('#menu_rel').addClass('d-none');
    }
    // 各链接方式是否展开
    if (!treeNode.isParent) {
        $('#permission_add').addClass('d-none');
        $('#permission_edit').removeClass('d-none');
        $('#permission_del').removeClass('d-none');
        $('.ibox-tools .dropdown-toggle').removeClass('d-none');
    } else if (treeNode.ccount == 0) {
        $('#permission_add').removeClass('d-none');
        $('#permission_edit').addClass('d-none');
        $('#permission_del').addClass('d-none');
        $('.ibox-tools .dropdown-toggle').removeClass('d-none');
    } else {
        $('#permission_add').addClass('d-none');
        $('#permission_edit').addClass('d-none');
        $('#permission_del').addClass('d-none');
        $('.ibox-tools .dropdown-toggle').addClass('d-none');
    }
    $('#menu_detail').removeClass('d-none');
    // 展开节点
    zTreeObj.expandNode(treeNode, null, null, null, true);
}

// 异步加载数据过滤
function filter(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    return childNodes;
}

// 异步加载成功数据处理
function onAsyncSuccess(event, treeId, treeNode, msg) {
    if (!treeNode) return null;
    for (let i = 0, len = treeNode.children.length; i < len; i++) {
        node_info[treeNode.children[i].id] = treeNode.children[i];
    }
    treeNode.ccount = treeNode.children.length;
    if (treeNode.id != 0) {
        treeNode.name = treeNode.show_name + "(c:" + treeNode.ccount + ")";
    }
    zTreeObj.updateNode(treeNode);
}

let setting = {
    async: {
        enable: true,
        url: menu_list_url,
        type: "get",
        autoParam: ["id", "name", "level"],
        otherParam: {"nodeload": true},
        dataFilter: filter
    },
    edit: {
        enable: true,
        editNameSelectAll: true,
        showRemoveBtn: showRemoveBtn,
        showRenameBtn: showRenameeBtn,
    },
    view: {
        fontCss: {'color': 'black', 'font-weight': 'bold'},//字体样式函数
        addHoverDom: addHoverDom,
        removeHoverDom: removeHoverDom,
    },
    data: {
        keep: {parent: true},
        key: {title: "title"},
    },
    callback: {
        beforeExpand: beforeExpand,
        onExpand: onExpand,
        onClick: onClick,
        beforeRemove: beforeRemove,
        beforeEditName: beforeEditName,
        onAsyncSuccess: onAsyncSuccess,
    }
};
zTreeObj = $.fn.zTree.init($("#MenuTree"), setting);

$('#menu_detail_name a').click(clickforrel);

$('.menu_box_close').click(function () {
    ibox = $(this).closest('div.ibox').parent();
    if (ibox.attr('id') == "menu_rel") {
        ibox.addClass('d-none');
    } else {
        ibox.addClass('d-none');
        $('#menu_rel').addClass('d-none');
    }
});

$('#permission_add').click(function () {
    event.stopPropagation();
    success_flag = false;
    selectednode = zTreeObj.getSelectedNodes()[0];
    if (selectednode.ccount > 0 || !selectednode.isParent) {
        swal({
            title: "无法添加权限！",
            text: "此节点下有子节点，请确保此节点下没有子节点再进行添加权限！",
            icon: "error",
            button: " 确 定 ",
        });
        return false;
    }
    url = $('#permission_add').attr('href');
    $.ajax({
        url: url,
        success: function (data) {
            $('#MenuModal .modal-body').html(data);
            $('#MenuModal .modal-title').text("添加权限");
            $('#MenuModal .modal-header small').text("");
            $('#MenuModal .modal_btn').unbind().bind('click', add_permission).removeClass('d-none');
            $('#MenuModal #id_title').val(selectednode.show_name);
            $('#MenuModal #id_rel').val(selectednode.id);
            $('#MenuModal').modal('show');
        },
        error: function (data) {
            console.log(data);
        }
    });
    return false;
});

$('#permission_edit').click(function () {
    event.stopPropagation();
    success_flag = false;
    selectednode = zTreeObj.getSelectedNodes()[0];
    if (selectednode.isParent) {
        swal({
            title: "无法修改权限！",
            text: "此节点无权限，请确认后再重试！",
            icon: "error",
            button: " 确 定 ",
        });
        return false;
    }
    url = $('#permission_edit').attr('href').replace('0', selectednode.perid);
    $.ajax({
        url: url,
        success: function (data) {
            $('#MenuModal .modal-body').html(data);
            $('#MenuModal .modal-title').text("修改权限");
            $('#MenuModal .modal-header small').text("");
            $('#MenuModal .modal_btn').unbind().bind('click', edit_permission).removeClass('d-none');
            $('#MenuModal').modal('show');
        },
        error: function (data) {
            console.log(data);
        }
    });
    return false;
});

$('#permission_del').click(function () {
    selectednode = zTreeObj.getSelectedNodes()[0];
    let url = $(this).attr('href').replace('0', selectednode.perid);
    if (selectednode.isParent) {
        swal({
            title: "无法删除！",
            text: "此节点没有权限，无法删除！",
            icon: "error",
            button: " 确 定 ",
        });
        return false;
    }
    swal({
        title: "Are you sure?",
        text: "Once deleted, you will not be able to recover this permission!",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willDelete) => {
        if (willDelete) {
            $.ajax({
                url: url,
                type: "POST",
                data: $('.ibox-content form').serialize(),
                dataType: 'json',
                success: function (data) {
                    parent_node = selectednode.getParentNode();
                    if (data['status'] == 0) {
                        swal({
                            title: "删除成功！",
                            text: "此权限已经成功删除",
                            icon: "success",
                            button: " 确 定 ",
                        });
                        zTreeObj.reAsyncChildNodes(parent_node, 'refresh');
                        $('#menu_detail').addClass('d-none');
                        $('#menu_rel').addClass('d-none');
                    } else {
                        swal({
                            title: "删除失败！",
                            text: "权限删除失败，失败原因是: " + data['info'],
                            icon: "warning",
                            button: " 确 定 ",
                        });
                    }
                },
                error: function (data) {
                    console.log(data);
                }
            });
        }
    });
    return false;
});
